package com.education.wisdom.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.education.common.config.BusinessException;
import com.education.common.config.CommonErrorCode;
import com.education.common.config.WebSocketServer;
import com.education.common.pojo.ResourceVO;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.DateUtil;
import com.education.common.utils.FileGetSizeUtil;
import com.education.wisdom.feign.UserFeign;
import com.education.wisdom.feign.WelcoFeign;
import com.education.wisdom.pojo.*;
import com.education.wisdom.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.*;


/**
 * 学校课程资源表
 *
 * @date 2020-07-09 14:51:34
 */
@RestController
@RequestMapping("/web/lessonResources")
public class FullLessonResourcesController {

    @Autowired
    private LessonResourcesService lessonResourcesService;

    @Autowired
    private LessonMenuService lessonMenuService;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private WelcoFeign welcoFeign;

    @Autowired
    private LessonLabelService lessonLabelService;

    @Autowired
    private LessonresourceUserBuyService lessonresourceUserBuyService;

    @Autowired
    private ICurrencyRecordService currencyRecordService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MessageService messageService;

    @Autowired
    private RulesService rulesService;

    @Autowired
    private ICatalogService catalogService;

    /**
     * 查询备课资源我的购买
     */
    @GetMapping("/lessonBuy")
    public ApiReturnObject lessonBuy(Integer userId, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        if (userId == null) {
            return new ApiReturnObject("300", "操作失败", "userid为空");
        }
        List<LessonResources> resourcesList = lessonResourcesService.selectLessonBuyByUserId(userId.toString());
        getCatalog(userId, resourcesList);
        return new ApiReturnObject("200", "操作成功", new PageInfo<LessonResources>(resourcesList));
    }

    private void getCatalog(Integer userId, List<LessonResources> resourcesList) {
        for (LessonResources resources : resourcesList) {
            if (resources.getLessonId() != null) {
                LessonMenu lessonMenu = lessonMenuService.selectLessonMenuById(resources.getLessonId());
                resources.setLesson(lessonMenu.getName());//专业
            }
            if (resources.getRCreateuser() != null) {
                Map<String, Object> map = userFeign.selectByUserId(resources.getRCreateuser());
                if (null != map && map.size() > 0 && StringUtils.isNotBlank(map.get("name").toString())) {
                    resources.setTeacherName(map.get("name").toString());//老师姓名
                    resources.setTeacherImage(map.get("image").toString());//老师姓名
                }
                Integer count = lessonResourcesService.selectCountByUserId(resources.getRCreateuser());
                resources.setCount(count);//老师上传课件总数
            }
            //查询课程是否购买
            LessonresourceUserBuy buy = new LessonresourceUserBuy();
            buy.setResourceId(resources.getId());
            buy.setUserId(userId);
            List<LessonresourceUserBuy> list = lessonresourceUserBuyService.selectList(buy);
            if (list.size() > 0) {
                resources.setIsRed(1);//已购买
            } else {
                resources.setIsRed(0);//未购买
            }
            if (resources.getImage() != null && !"".equals(resources.getImage())) {
                String[] split = resources.getImage().split(",");
                resources.setPreviewArray(split);
            }
        }
    }

    @GetMapping("/findById")
    public ApiReturnObject findById(Integer id) {
        List<Catalog> catalogs = catalogService.selectByCatalogId(id);
        if (catalogs.size() > 0) {
            return new ApiReturnObject("200", "查询成功", catalogs.get(0));
        } else {
            return new ApiReturnObject("200", "查询成功", new Catalog());
        }
    }

    /**
     * 查询所有资源
     */
    @GetMapping("/selectAll")
    public ApiReturnObject selectAll(LessonResources lessonResources, Integer userId, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        if (userId != null) {
            lessonResources.setRCreateuser(null);
        }
        //查询未下线资源
        lessonResources.setDelFlag("1");
        //查询审核通过资源
        lessonResources.setExamine("1");
        List<LessonResources> resourcesList = lessonResourcesService.selectLessonResourcesList(lessonResources);
        for (LessonResources resources : resourcesList) {
            resources.setUrlArray(resources.getRUrl().split(","));
        }
        getCatalog(userId, resourcesList);
        return new ApiReturnObject("200", "success", new PageInfo<LessonResources>(resourcesList));
    }

    /**
     * 上传资源
     */
    @PostMapping("/ins")
    public ApiReturnObject insert(@RequestBody LessonResources lessonResources) {
        //用户前5次上传赠送达人币 5
        String time = DateUtil.getCurrentDateTime();//获取当前时间
        Integer integer = lessonResourcesService.selectCountByUserIdAndTime(lessonResources.getRCreateuser(), time);
        if (integer <= 5) {
            //查询用户达人币
            Map<String, Object> use = userFeign.selectByUserId(lessonResources.getRCreateuser());
            BigDecimal price = new BigDecimal(use.get("price").toString());
            //修改用户达人币
            Map<String, Object> map = new HashMap<>();
            map.put("id", lessonResources.getRCreateuser());
            //map.put("price", price + 5);
            map.put("price", price.add(new BigDecimal(5)));
            userFeign.updataByUserId(map);
        }
        lessonResources.setCreateTime(new Date());
        lessonResources.setDelFlag("1");

        String size = "";
        try {
            //获取资源大小
            size = FileGetSizeUtil.getQiNiuUrl2(lessonResources.getRUrl());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        lessonResources.setRSize(size);
        StringBuilder sb = new StringBuilder();
        for (String ico : lessonResources.getPreviewArray()) {
            sb.append(ico).append(",");
        }
        String s = "";
        if (!"".equals(sb.toString())) {
            s = sb.toString().substring(0, sb.toString().length() - 1);//去掉最后一个 ,
        }
        lessonResources.setImage(s);
        lessonResources.setRUploadtime(DateUtil.getCurrentTime());
        int i = lessonResourcesService.insertLessonResources(lessonResources);
        //添加到我的购买
        LessonresourceUserBuy lessonresourceUserBuy = new LessonresourceUserBuy();
        lessonresourceUserBuy.setCreatetime(new Date());
        lessonresourceUserBuy.setDeflag("1");
        lessonresourceUserBuy.setUserId(lessonResources.getRCreateuser());
        lessonresourceUserBuy.setResourceId(lessonResources.getId());
        lessonresourceUserBuyService.insertLessonresourceUserBuy(lessonresourceUserBuy);
        if (i > 0) {
            return new ApiReturnObject("200", "上传成功", "上传成功");
        }
        throw new BusinessException(CommonErrorCode.E_200108);
    }

    /**
     * 删除
     */
    @GetMapping("/delete")
    public ApiReturnObject deleteById(String ids) {
        lessonResourcesService.deleteLessonResourcesByIds(ids);
        return new ApiReturnObject("200", "删除成功", "删除成功");
    }


    /**
     * 备课共享资源购买
     * liftsail add 同步资源到智慧云4.0我的资源库
     */
    @PostMapping("/buy")
    @Transactional
    public ApiReturnObject buy(@RequestBody LessonResources lesson) {
        //查询该资源
        LessonResources lessonResources = lessonResourcesService.selectLessonResourcesById(lesson.getResourceId());
        //课程价格
        BigDecimal lessonPrice = new BigDecimal(lessonResources.getPrice());
        //查询购买用户的达人币
        Map<String, Object> buyUserId = userFeign.selectByUserId(lesson.getUserId());
        BigDecimal buyPrice = new BigDecimal(buyUserId.get("price").toString());
        //查询上传用户达人币
        Map<String, Object> upUserId = userFeign.selectByUserId(lessonResources.getRCreateuser());
        BigDecimal upPrice = new BigDecimal(upUserId.get("price").toString());
        //用户不能购买自己课程
        Integer userId = lesson.getUserId();
        Integer createuser = lessonResources.getRCreateuser();
        if (userId.equals(createuser)) {
            return new ApiReturnObject("201", "购买失败", "用户不能购买自己课程");
        }

        //查询该资源是否已被该用户购买
        LessonresourceUserBuy userBuy = new LessonresourceUserBuy();
        userBuy.setUserId(lesson.getUserId());
        userBuy.setResourceId(lesson.getResourceId());
        userBuy.setDeflag("1");
        List<LessonresourceUserBuy> buyList = lessonresourceUserBuyService.selectLessonresourceUserBuyList(userBuy);
        if (buyList.size() > 0) {
            return new ApiReturnObject("201", "购买失败", "用户已购买该课程");
        }

        //购买修改达人币数量
        if (buyPrice.compareTo(BigDecimal.ZERO) == 0) {
            //购买用户达人币为空
            return new ApiReturnObject("201", "购买失败", "达人币为空");
        }
        BigDecimal price = buyPrice.subtract(lessonPrice);
        //Integer price = buyPrice - lessonPrice;
        if (price.compareTo(BigDecimal.ZERO) < 0) {
            return new ApiReturnObject("201", "购买失败", "达人币不足");
        }
        //-------------------------购买业务start-------------------------
        //resourceId: 2078  备课共享资源资源id
        //userId: 1207      老师userId
        //类型 1 文档 4 图片 5 视频     type_id
        //-------------------------资源同步业务start-------------------------
        lessonResourcesService.lessonsSharedSynchronousMineRes(lesson.getResourceId(), lesson.getUserId());
        // -------------------------资源同步业务end-------------------------
        //修改购买用户达人币
        Map<String, Object> map = new HashMap<>();
        map.put("id", lesson.getUserId());
        map.put("price", price);
        //userFeign.updataByUserId(map);
        userFeign.updatePriceByUserId(lesson.getUserId(), price);
        //修改上传用户达人币
        CurrencyRecord record = new CurrencyRecord();
        CurrencyRecord record2 = new CurrencyRecord();
        Rules rules = rulesService.selectRulesById(1);//查询备课资源扣除规则
        if (!"0".equals(rules.getProportion().toString())) {
            //BigDecimal lessonPriceInt = new BigDecimal(lessonPrice);
            BigDecimal lessonPriceInt = lessonPrice;
            BigDecimal rule = rules.getProportion();
            BigDecimal decimal = new BigDecimal(100);
            BigDecimal divide = rule.divide(decimal, 1, BigDecimal.ROUND_HALF_UP);

            BigDecimal subtract = lessonPriceInt.subtract(lessonPriceInt.multiply(divide, MathContext.UNLIMITED));
            Map<String, Object> map1 = new HashMap<>();
            map.put("id", lessonResources.getRCreateuser());
            String s = StringUtils.substringBeforeLast(subtract.toString(), ".");
            //map.put("price", upPrice + Integer.parseInt(s));
            map.put("price", upPrice.add(new BigDecimal(s)));
            userFeign.updataByUserId(map);

            record.setCurrency(new BigDecimal(s));
            record2.setCurrency(new BigDecimal(-Integer.parseInt(s)));
        } else {
            Map<String, Object> map1 = new HashMap<>();
            map.put("id", lessonResources.getRCreateuser());
            //map.put("price", upPrice + lessonPrice);
            map.put("price", lessonPrice.add(upPrice));
            userFeign.updataByUserId(map);
            record.setCurrency(new BigDecimal(lessonResources.getPrice()));
            record2.setCurrency(new BigDecimal(-lessonResources.getPrice()));
        }

        //添加到购买表
        LessonresourceUserBuy buy = new LessonresourceUserBuy();
        buy.setUserId(lesson.getUserId());
        buy.setResourceId(lesson.getResourceId());
        buy.setDeflag("1");
        buy.setCreatetime(new Date());
        lessonresourceUserBuyService.insertLessonresourceUserBuy(buy);

        //添加支付记录
        record.setCreateTime(new Date());
        record.setUserId(lesson.getUserId().toString());
        record.setPayerName(upUserId.get("name").toString());

        record.setRemark("备课资源购买");
        record.setCatalogId(lesson.getResourceId());
        record.setTrxType("3");
        record.setStatus("1");
        currencyRecordService.insertCurrencyRecord(record);

        record2.setCreateTime(new Date());
        record2.setUserId(lessonResources.getRCreateuser().toString());
        record2.setPayerName(buyUserId.get("name").toString());

        record2.setRemark("备课资源售出");
        record2.setCatalogId(lesson.getResourceId());
        record2.setTrxType("5");
        record2.setStatus("1");
        currencyRecordService.insertCurrencyRecord(record2);

        //添加购买消息
        inserMessage(lesson, lessonResources);

        return new ApiReturnObject("200", "购买成功", price);
    }

    //添加购买消息
    private void inserMessage(@RequestBody LessonResources lesson, LessonResources lessonResources) {
        Message message = new Message();
        message.setIsRead("1");
        message.setUserId(lesson.getUserId());
        message.setType("1");
        message.setCreatetime(new Date());
        message.setTitle("您已购买课程 : " + lessonResources.getRName());
        messageService.insertMessage(message);
        //发送消息
        Integer count = messageService.selectCount(lesson.getUserId().toString());
        try {
            WebSocketServer.sendInfo(count.toString(), lesson.getUserId().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        Message mess = new Message();
        mess.setIsRead("1");
        mess.setUserId(lessonResources.getRCreateuser());
        mess.setType("1");
        mess.setCreatetime(new Date());
        mess.setTitle("您的课程已经被购买 : " + lessonResources.getRName());
        messageService.insertMessage(mess);
        //发送消息
        Integer coun = messageService.selectCount(lessonResources.getRCreateuser().toString());
        try {
            WebSocketServer.sendInfo(coun.toString(), lessonResources.getRCreateuser().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 同步
     *
     * @param ids       资源id
     * @param catalogId 课程id
     * @return
     */
    @GetMapping("/synchronous")
    public ApiReturnObject synchronous(String ids, Integer catalogId, Integer userId) {
        Object count = redisTemplate.opsForValue().get("count" + userId);
        int i = 0;
        if (count == null) {
            count = 1;
        }
        i = Integer.parseInt(count.toString());
        if (i <= 5) {
            //查询用户达人币
            Map<String, Object> use = userFeign.selectByUserId(userId);
            BigDecimal price = new BigDecimal(use.get("price").toString());
            //修改用户达人币
            Map<String, Object> map = new HashMap<>();
            map.put("id", userId);
            Random random = new Random();
            int j = random.nextInt(5) + 1;
            //map.put("price", price + j);
            map.put("price", price.add(new BigDecimal(j)));
            userFeign.updataByUserId(map);
        }
        redisTemplate.opsForValue().set("count" + userId, i + 1);
        List<LessonResources> resourcesList = lessonResourcesService.selectByIds(ids);
        if (resourcesList.size() > 0) {
            for (LessonResources resources : resourcesList) {
                ResourceVO vo = new ResourceVO();
                vo.setRUrl(resources.getRUrl());
                vo.setRName(resources.getRName());
                vo.setCatalogId(catalogId);
                vo.setRSize(resources.getRSize());
                vo.setType(resources.getTypeId().toString());
                vo.setImage(resources.getResIco());
                welcoFeign.lessonResource(vo);
            }
        }
        return new ApiReturnObject("200", "操作成功", "操作成功");
    }

    /**
     * 逻辑删除我的购买
     */
    @PostMapping("/delete")
    public ApiReturnObject delete(@RequestBody LessonresourceUserBuy lessonresourceUserBuy) {
        lessonresourceUserBuy.setDeflag("0");
        int i = lessonresourceUserBuyService.updateLessonresourceUserBuy(lessonresourceUserBuy);
        if (i > 0) {
            return new ApiReturnObject("200", "操作成功", "操作成功");
        }
        return new ApiReturnObject("201", "操作失败", "操作失败");
    }
}
